<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/12
  Time: 17:45
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>客户订单</title>
   	<jsp:include page="../headPage.jsp"></jsp:include>
    <script type="text/javascript">
    
    function toastrStyle(){
    	toastr.options = {
                "closeButton": false,
                "debug": false,
                "newestOnTop": false,
                "progressBar": false,
                "positionClass": "toast-top-center",
                "preventDuplicates": false,
                "onclick": null,
                "showDuration": "5000",
                "hideDuration": "1000",
                "timeOut&quot": "100000",
                "extendedTimeOut": "0",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            }; 
    }
    
    $(function () {

            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();
            oButtonInit.Init();

            //行点击事件
            $('#tb_departments').on('click-row.bs.table', function (e, row, element) {initBottomTable(row.id);});

        });


        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#tb_departments').bootstrapTable({
                    url: '${pageContext.request.contextPath }/yzl/returnList.do',         //请求后台的URL（*）
                    method: 'post',                      //请求方式（*）
                    contentType:"application/x-www-form-urlencoded; charset=UTF-8",
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    //striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    //sortable: false,                     //是否启用排序
                    //sortOrder: "asc",                   //排序方式
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [10, 20, 30],        //可供选择的每页的行数（*）
                    //strictSearch: true,
                    //singleSelect : true, // 单选checkbox
                    maintainSelected: false,
                    minimumCountColumns: 2,             //最少允许的列数
                    //clickToSelect: true,                //是否启用点击选中行
                    height: 400,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    columns: [{
                        checkbox: true
                    }, /*{
                        field: 'id',
                        title: 'ID'
                    },*/ {
                        field: 'returnsNumber',
                        title: '退货编号'
                    }, {
                        field: 'returnsDate',
                        title: '退货日期'
                    }, {
                        field: 'customerName',
                        title: '客户'
                    },
                        {
                            field: 'returnsStatus',
                            title: '状态',
                            formatter:function(value, row, index){
                                if(value == 0){
                                    return '处理中'
                                }else if(value == 1){
                                    return '退货成功'
                                }else{
                                    return 'WTF'
                                }
                            }
                        }, {
                            field: 'returnsExamineStatus',
                            title: '审批状态',
                            formatter: function (value, row, index) {
                                var back = index;
                                if (value == "0") {
                                    return '未提交'
                                } else if (value == "1") {
                                    return '审批中'
                                } else if (value == "2") {
                                    return '审批完成'
                                } else if (value == "3") {
                                    return '审批未通过'
                                } else {
                                    return 'WTF'
                                }
                            }
                        }]
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset / params.limit + 1,  //页码
                    recent: $("#recent").val(),
                    beginDate: $("#beginDate").val(),
                    endDate: $("#endDate").val(),
                    customerName: $("#customerName").val(),
                };
                return temp;
            };
            return oTableInit;
        };


        var ButtonInit = function () {

            var oInit = new Object();
            var postdata = {};

            oInit.Init = function () {
                //初始化页面上面的按钮事件
            };
            return oInit;
        };
        
        $(function() {
        	//执行后台
            $.ajax({
                url: "${pageContext.request.contextPath}/hpf/customerAllList.do",
                type: "post",
                success: function (data) {
                	//var row = data.rows;
                	for(var i=0;i<data.length;i++){
                    	console.log(data[i]);
                		//添加option
                    	$("#customerName").append('<option value="'+data[i].id+'">' + data[i].name + '</option>');
                	}
                }
            })
		})
    </script>
</head>
<body>
<div class="panel-body" style="padding-bottom:0px;">
	<!--   查询条件  -->
	<div class="panel panel-default">
	    <div class="panel-body">
	        <form id="formSearch" class="form-horizontal">
	            <label class="control-label col-sm-1">日期:</label>
	            <div class="col-sm-2">
	                <select id="recent" name="recent"
	                        class="selectpicker show-tick form-control" data-live-search="false">
	                    <option value="0">所有时间</option>
	                    <option value="1">最近一天</option>
	                    <option value="7">最近一星期</option>
	                    <option value="30">最近一个月</option>
	                </select>
	            </div>
	            <label class="control-label col-sm-1" for="beginDate" style="width: 30px;">从</label>
	            <div class="col-sm-2">
	                <input type="text" name="beginDate" id="beginDate" placeholder="yyyy-mm-dd" class="form_datetime form-control">
	            </div>
	            <label class="control-label col-sm-1" for="endDate" style="width: 30px;padding-left: 0px;">至</label>
	            <div class="col-sm-2" style="padding-left: 0px;">
	                <input type="text" name="endDate" id="endDate" placeholder="yyyy-mm-dd" class="form_datetime form-control">
	            </div>
	            <label class="control-label col-sm-1" for="customerName">相关客户:</label>
	            <div class="col-sm-1">
	                <select id="customerName" name="customerName"
	                        class="selectpicker show-tick form-control">
	                    <option>所有客户</option>
	                </select>
	            </div>
	            <div class="col-sm-1">
	                <button type="button" id="btn_query" class="btn btn-primary">查询</button>
	            </div>
	            <!-- <div class="col-sm-1">
	                <button type="button" id="btn_query1" class="btn btn-default">清除</button>
	            </div> -->
	            <%--</div>--%>
	        </form>
	    </div>
	</div>
	
	<!--  新增 ==按钮列表  -->
	<div id="toolbar" class="btn-group">
	    <button id="btn_add" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
	    </button>
	    <button id="btn_edit" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
	    </button>
	    <button id="btn_delete" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
	    </button>
	    <button id="btn_approved" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-phone" aria-hidden="true"></span>审批
	    </button>
	    <button id="btn_Undoapproved" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>撤销审批
	    </button>
	    <button id="btn_Returns" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>退货处理
	    </button>
	    <button id="btn_Export" type="button" class="btn btn-default">
	        <span class="glyphicon glyphicon-inbox" aria-hidden="true"></span>导出
	    </button>
	</div>
	
	<!--        表格           -->
	<table id="tb_departments" style="font-size: 14px;"></table>
	
	<!--    底部详情表格   -->
	<div id="bottomTableDiv"></div>
	<%--<table id="tb_details"></table>--%>
	
	<!--          修改表单       -->
	<div class="modal fade" id="updateNumberModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	    <div class="modal-dialog" style="width: 70%;height: 60%">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                <h4 class="modal-title" id="updateModalLabel">新增订单</h4>
	            </div>
	
	            <input hidden="hidden" id="updateCustomerId">
	            <input hidden="hidden" id="updateOrderNumId">
	            <div id="updateModelTable_outDiv"></div>
	
	            <div class="modal-footer">
	                <button type="button" class="btn btn-primary" style="float:left" id="btn_updateIn">添加产品</button>
	                <button type="button" class="btn btn-primary" style="float:left">删除产品</button>
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                <button type="button" class="btn btn-primary" id="btn_update">确定</button>
	            </div>
	        </div><!-- /.modal-content -->
	    </div><!-- /.modal-dialog -->
	</div>
	
	<!--          添加表单       -->
	<div class="modal fade" id="addNumberModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	    <div class="modal-dialog" style="width: 70%;height: 60%">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                <h4 class="modal-title" id="myModalLabel">新增订单</h4>
	            </div>
	
	            <input hidden="hidden" id="customerId">
	
	            <div id="addModelTable_outDiv"></div>
	
	            <div class="modal-footer">
	                <button type="button" class="btn btn-primary" style="float:left" id="btn_addIn">添加产品</button>
	                <button type="button" class="btn btn-primary" style="float:left">删除产品</button>
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                <button type="button" class="btn btn-primary" id="btn_save">确定</button>
	            </div>
	        </div><!-- /.modal-content -->
	    </div><!-- /.modal-dialog -->
	</div>
	
	<!--          客户选择表单       -->
	<div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	    <div class="modal-dialog" style="width: 60%;height: 50%">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                <h4 class="modal-title" id="customerModalLabel">新增订单</h4>
	            </div>
	
	            <table id="td_customerTable"></table>
	
	            <div class="modal-footer">
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                <button type="button" class="btn btn-primary" onclick="backCus()" id="backCus">确定</button>
	            </div>
	        </div><!-- /.modal-content -->
	    </div><!-- /.modal-dialog -->
	</div>
	
	<!--          客户选择表单       -->
	<div class="modal fade" id="proListModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	    <div class="modal-dialog" style="width: 60%;height: 50%">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                <h4 class="modal-title" id="proListModalLabel">新增订单</h4>
	            </div>
	
	            <table id="td_proListTable"></table>
	
	            <div class="modal-footer">
	                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	                <button type="button" class="btn btn-primary" onclick="backPro()" id="backPro">确定</button>
	            </div>
	        </div><!-- /.modal-content -->
	    </div><!-- /.modal-dialog -->
	</div>
	
	
	<!--    删除   -->
	<div class="modal fade" id="myModalDelete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	    <div class="modal-dialog" style="width: 60%;height: 50%">
	        <div class="modal-content">
	            <div class="modal-header">
	                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
	                <h4 class="modal-title" id="myModalDeleteLabel">删除订单</h4>
	            </div>
	
	
	
	            <div class="modal-footer">
	                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
	                <button type="button" class="btn btn-primary" onclick="deleteOrder()">确定删除</button>
	            </div>
	        </div><!-- /.modal-content -->
	    </div><!-- /.modal-dialog -->
	
	</div>
</div>

<script>

    $(function (){
        $("#btn_Undoapproved").click(function (){Undoapproved()});
    })

    //点击保存新增订单
    $("#btn_save").click(function () {
        //得到原来的表格数据
        var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
        //循环将填写的数量填入表格
        for(var i=0;i<allTableData.length;i++){
            var count = $("#addTIndex"+allTableData[i].id).val();
            allTableData[i].planQ = count;
            allTableData[i][0] = undefined;
        }
        //得到选择的客户ID
        var customerId = $("#customerId").val();
        var obj = dedaoValue("td_addModelTable");
        var obj1 = {
            number : obj.number,
            customerId : customerId,
            planDate : obj.time,
            productors : allTableData
        };
        $.ajax({
            url : "${pageContext.request.contextPath }/yzl/addReturnFrom.do",
            type : "POST",
            data : JSON.stringify(obj1),
            contentType: "application/json; charset=utf-8",
            dataType : "json",
            success : function(data){
                if(data == 1){
                	toastrStyle();
                	toastr.warning("保存成功！");
                    //关闭模态框
                    $("#addNumberModal").modal('hide');
                    //$("#btn_save").attr("data-dismiss","modal");
                }else{
                	toastr.warning("保存失败！");
                }
            }
        })

    })

    $("#btn_query").click(function (){refreshAjax();})

    //清除输入的条件
    $("#btn_query1").click(function (){$("#beginDate").val("");$("#endDate").val("");})

    $("#btn_delete").click(function () {

    	//必须选中一条数据
    	var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
        if(checkedItems <= 0){
        	toastrStyle();
            toastr.warning('请选择一行信息');
        }else{
            console.log("checkedItems----",checkedItems);
            var arr1 = filterData(checkedItems);
            if(arr1){
            	var arr2 = filterOutData(checkedItems);
                if(arr2){
                	console.log(arr2);
                	//询问框
            		Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
            		function(e) {
            				if (!e) {return;}
            				$.ajax({
                                url: "${pageContext.request.contextPath}/yzl/deleteReturn.do",
                                type: "post",
                                data: {"arr": JSON.stringify(arr2)},
                                success: function (data) {
                                    if (data != 0) {
                                    	toastrStyle();
                                        toastr.success('删除成功');
                                        refreshAjax();
                                    } else {
                                    	toastrStyle();
                                        toastr.warning('删除失败');
                                    }
                                }
                            })
            			});
                }else{
                	toastrStyle();
                    toastr.warning('不能删除已退货的退货记录');
                }
            }else{
            	toastrStyle();
                toastr.warning('不能删除审核中或已审核的退货记录');
            }
        }
    });

    function deleteOrder(){

        var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
            //var checkedItem = checkedItems[0];
            var list=new Array(checkedItems.length);
            $("#myModalDelete").modal('hide');
            //comAjax("${pageContext.request.contextPath}/yzl/deleteOrder.do",{id:list},function(data){})
            var arr1 = filterData(checkedItems);
            if (arr1) {
            	var arr2 = filterOutData(checkedItems);
                if (arr2) {
                    //执行后台
                    $.ajax({
                        url: "${pageContext.request.contextPath}/yzl/deleteReturn.do",
                        type: "post",
                        data: {"arr": JSON.stringify(arr2)},
                        success: function (data) {
                            if (data != 0) {
                                toastr.info('操作成功');
                                refreshAjax();
                            } else {
                                toastr.warning('操作失败');
                            }
                        }
                    })
                }
            }
	        window.location.href = "${pageContext.request.contextPath }/pages/yzlERP/return/salesReturns.jsp";
    }

    //提交审核
    $("#btn_approved").click(function () {
        //必须选中一条数据
        var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
        console.log(checkedItems);
        if (checkedItems <= 0) {
            //$("#btn_edit").attr("data-toggle", "");
            //$("#btn_edit").attr("data-target", "");
            toastrStyle();
            toastr.warning('请选择一行信息');
        } else {
            var arr = filterData(checkedItems);
            if (arr) {
                //执行后台
                $.ajax({
                    url: "${pageContext.request.contextPath}/yzl/returnApproveds.do",
                    type: "post",
                    data: {"arr": JSON.stringify(arr)},
                    success: function (data) {
                        if (data != 0) {
                        	toastrStyle();
                            toastr.info('提交审批成功');
                            refreshAjax();
                        } else {
                        	toastrStyle();
                            toastr.warning('提交审批失败');
                        }
                    }
                })
            } else {
            	toastrStyle();
                toastr.warning('只能选择未审批的退货记录');
            }
        }
    });

    //撤销审核
    function Undoapproved(){
        //必须选中一条数据
        var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
        var checkedItem = checkedItems[0];
        if (checkedItems <= 0) {
            //$("#btn_edit").attr("data-toggle", "");
            //$("#btn_edit").attr("data-target", "");
            toastrStyle();
            toastr.warning('请选择一行信息');
        } else {
            var arr = filterDataUn(checkedItems);
            if (arr) {
                //执行后台
                $.ajax({
                    url: "${pageContext.request.contextPath}/yzl/returnUnApproveds.do",
                    type: "post",
                    data: {"arr": JSON.stringify(arr)},
                    success: function (data) {
                        if (data != 0) {
                        	toastrStyle();
                            toastr.info('撤销审批成功');
                            refreshAjax();
                        } else {
                        	toastrStyle();
                            toastr.warning('撤销审批失败');
                        }
                    }
                })
            } else {
            	toastrStyle();
                toastr.warning('只能选择审批中的信息');
            }
        }
    }
    
  	//退货处理
    $("#btn_Returns").click(function () {
        //必须选中一条数据
        var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
        console.log(checkedItems);
        if (checkedItems <= 0) {
            //$("#btn_edit").attr("data-toggle", "");
            //$("#btn_edit").attr("data-target", "");
            toastrStyle();
            toastr.warning('请选择一行信息');
        } else {
            var arr = filterOutData(checkedItems);
            var arr1 = filterOutData2(checkedItems);
            if (arr1) {
            	if (arr) {
            		//执行后台
                    $.ajax({
                        url: "${pageContext.request.contextPath}/yzl/returnProcess.do",
                        type: "post",
                        data: {"arr": JSON.stringify(arr)},
                        success: function (data) {
                            if (data != 0) {
                            	toastrStyle();
                                toastr.info('退货成功');
                                refreshAjax();
                            } else {
                            	toastrStyle();
                                toastr.warning('退货失败');
                            }
                        }
                    })
				} else {
					toastrStyle();
	                toastr.warning('不能选择已退货的记录');
				}
            } else {
            	toastrStyle();
                toastr.warning('只能选择审批完成的记录');
            }
        }
    });
    
  	//导出
    $("#btn_Export").click(function (){
    	//询问框
		Ewin.confirm({message : "确认要导出所有数据吗？"}).on(
			function(e) {
				if (!e) {return;}
				window.location.href="${pageContext.request.contextPath}/yzl/returnImport.do"
			});
    })

    $("#btn_addIn").click(function (){initProductorsTable();})

    //选择客户
    function choseCustomer(){initCustomerTable()}

    //选择客户 返回带回数据 关闭第二层模态框 第一层模态框表格重新加载
    function backCus(){

        //得到修改的ID
        var orderId = $("#updateOrderNumId").val();
        //得到选择的数据
        var rows = $('#td_customerTable').bootstrapTable('getSelections')[0];
        //得到原来的表头信息
        var objTable = dedaoValue("td_addModelTable");
        if(rows){
            //关闭第二层模态框
            $("#backCus").attr("data-dismiss","modal");
            //更新第一层模态框的表格
            initAddTable(objTable.number,objTable.time,rows.name,rows.name,"1111",rows.name,orderId);
            //给customerId赋值
            $("#customerId").val(rows.id);
            //给updateCustomerId赋值
            $("#updateCustomerId").val(rows.id);
        }else{
        	toastrStyle();
        	toastr.warning("请选择客户");
        }
    }

    //选择产品
    function backPro(){
        //得到修改的ID
        var orderId = $("#updateOrderNumId").val();
        //得到选择的数据
        var rows = $('#td_proListTable').bootstrapTable('getSelections');
        //得到原来的表格数据
        var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
        for(var j=0;j<rows.length;j++){
            allTableData.push(rows[j]);
        }
        //得到原来的表头信息
        var objTable = dedaoValue("td_addModelTable");
        if(rows){
            //关闭第二层模态框
            $("#backPro").attr("data-dismiss","modal");
            //更新第一层模态框的表格
            initAddTable(objTable.number,objTable.time,rows.name,objTable.customer,"1111",rows.name,orderId);

            for(var i=0;i<allTableData.length;i++){
                for(var x = 0;x<rows.length;x++){
                    if(rows[x].id != allTableData[i].id){
                        $('#td_addModelTable').bootstrapTable('insertRow', {
                            index:$('#td_addModelTable').bootstrapTable('getOptions').totalRows,
                            row:allTableData[i]
                        });
                    }
                }
            }


        }else{
        	toastrStyle();
        	toastr.warning("请选择客户");
        }
    }

    //关闭计划
    function closePlan(index) {
        var id = $("#tb_departments").bootstrapTable('getData')[index].id;
        $.ajax({
            url: "${pageContext.request.contextPath}/yzl/closePlan.do",
            type: "post",
            data: {"id": id},
            success: function (data) {
                if (data != 0) {
                	toastrStyle();
                    toastr.info('关闭成功');
                    refreshAjax();
                } else {
                	toastrStyle();
                    toastr.warning('关闭失败');
                }
            }
        })
    }


    //将产品添加至销售计划中
    function addToCusOrder() {}
    
  	//选中数据条件筛选（是否退货）
    function filterOutData(checkedItems){
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var returnsStatus = checkedItems[i].returnsStatus;
            if (returnsStatus == "1") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }
  	
  	//选中数据条件筛选（是否审批）
    function filterOutData2(checkedItems){
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
        	var returnsExamineStatus = checkedItems[i].returnsExamineStatus;
            if (returnsExamineStatus == "0" || returnsExamineStatus == "1") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }

    //选中数据条件筛选（撤销审批）
    function filterDataUn(checkedItems){
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var returnsExamineStatus = checkedItems[i].returnsExamineStatus;
            if (returnsExamineStatus == "2" || returnsExamineStatus == "0") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }

    //选中数据条件筛选
    function filterData(checkedItems) {
        var arr = new Array();
        for (var i = 0; i < checkedItems.length; i++) {
            var returnsExamineStatus = checkedItems[i].returnsExamineStatus;
            if (returnsExamineStatus == "2" || returnsExamineStatus == "1") {
                return false
            } else {
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }

    function makeRequirement() {
        $('#requirementModel').modal({
            keyboard: true,
        })
    }

    function tiJiao() {
        $('#layui-layer20').modal({
            keyboard: true,
        })
    }


    //统一请求ajax
    function comAjax(url,data,fuc){
        $.ajax({
            type:"POST",
            url:url,
            data:data,
            success:function (data) {
                fuc(data);
            },
        })
    }
    //点击查询 重新请求  刷新表格
    function refreshAjax() {
        $("#tb_departments").bootstrapTable('refresh', {url: '${pageContext.request.contextPath }/yzl/returnList.do'});
    }
</script>

<!--      表格初始化     -->
<script>

    //添加表格初始化
    function initAddTable(number,time,zhidanMan,customer,beforeNumber,approvedMan,id,modalId){
        var $addModelTable_outDiv = $("#addModelTable_outDiv");
        if($addModelTable_outDiv.find("table").length > 0){
            $addModelTable_outDiv.empty();
        }
        var table = '<table id="td_addModelTable"></table>'
        $addModelTable_outDiv.append(table);

        if(time == "" || time == null){
            time = '<input type="text" name="addTime" id="addTime" lay-verify="date"\n' +
                '                               placeholder="yyyy-mm-dd"\n' +
                '                               autocomplete="off" class="layui-input form-control"\n' +
                '                               onclick="layui.laydate({elem: this})">'
        }else{
            time = '<input type="text" name="addTime" id="addTime" lay-verify="date"\n' +
                '                               placeholder='+time+'\n' +
                '                               autocomplete="off" class="layui-input form-control"\n' +
                '                               onclick="layui.laydate({elem: this})" value="'+time+'">'
        }
        if(customer == "" || customer == null){
            customer = '<a href="#" onclick="choseCustomer()">选择客户</a>';
        }else{
            customer = '<a href="#" onclick="choseCustomer()">'+customer+'</a>';
        }

        newurl = "";
        if(id != "" || id !== null){
            newurl = "${pageContext.request.contextPath }/yzl/returnXq.do?id="+id;
        }

        $('#td_addModelTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            toolbar: '#toolbarIn',
            url : newurl,
            columns: [
                [
                    {
                        field: 'name',
                        title: "销售计划单",
                        valign: "middle",
                        align: "center",
                        colspan: 1
                    },
                    {
                        title: number,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: '计划时间',
                        valign: "middle",
                        align: "center",
                        colspan: 2,
                    },
                    {
                        title: time,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: "指定人",
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: zhidanMan,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    }
                ],
                [
                    {
                        field: 'name',
                        title: "客户",
                        valign: "middle",
                        align: "center",
                        colspan: 1
                    },
                    {
                        title: customer,
                        valign: "middle",
                        align: "center",
                        colspan: 4,
                    },
                    {
                        title: "审批人",
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                    {
                        title: approvedMan,
                        valign: "middle",
                        align: "center",
                        colspan: 1,
                    },
                ],
                [
                    {
                        field: 'cartype',
                        title: '车种',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'num',
                        title: '品编',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'name',
                        title: '品名',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'planQ',
                        title: '计划数量',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                            if(row.planQ > 0){
                                return '<input type="text" class="form-control" id="addTIndex'+row.id+'" value="'+row.planQ+'">'
                            }else{
                                return '<input type="text" class="form-control" id="addTIndex'+row.id+'">'
                            }
                            //return '<input type="text" class="form-control" value="'+row.outQ+'">'

                        }
                    },
                    {
                        field: 'unitPrice',
                        title: '单价',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'amount',
                        title: '金额',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'dayConsumptionQ',
                        title: '日消耗量',
                        valign: "middle",
                        align: "center"
                    }

                ]
            ]
        });
        $('#addNumberModal').modal({keyboard: true,});

        //$('#'+modalId).modal({keyboard: true,});
        //$("#toolbarIn").css("display","block");

    }

    //初始化客户表单
    function initCustomerTable(){
        $('#td_customerTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            singleSelect : true, // 单选checkbox
            //url: "/pages/yzlERP/data/customerList.json",
            url: "${pageContext.request.contextPath }/yzl/customerList.do",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'name',
                        title: "名称",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"age",
                        title: "年龄",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#customerModal").modal({keyboard: true,})
    }

    //初始化产品表单
    function initProductorsTable(){
        $('#td_proListTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            clickToSelect: true,    //是否启用点击选中行
            //singleSelect : true, // 单选checkbox
            //: "/pages/yzlERP/data/
            url: "${pageContext.request.contextPath }/yzl/carList.do",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'cartype',
                        title: "车种",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"name",
                        title: "品名",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"num",
                        title: "品编",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#proListModal").modal({keyboard: true,})
    }

    //底部详情列表初始化
    function initBottomTable(id){
        var $bottomTableDiv = $("#bottomTableDiv");
        if($bottomTableDiv.find("table").length > 0){
            url = "${pageContext.request.contextPath }/yzl/returnXq.do?id="+id;
            $("#tb_details").bootstrapTable('refresh', {url: url});
            //$bottomTableDiv.empty();
        }else{
            var table = '<table id="tb_details" style="font-size: 14px;"></table>'
            $bottomTableDiv.append(table);
        }

        $('#tb_details').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            toolbar: '#toolbarIn',
            url: "${pageContext.request.contextPath }/yzl/returnXq.do?id="+id,
            height:300,
            columns: [
                [
                    {
                        field: 'cartype',
                        title: '车种',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'num',
                        title: '品编',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'name',
                        title: '品名',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'returnQ',
                        title: '退库数量',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'remark8',
                        title: '单价',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'amount',
                        title: '金额',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                            return accMul(row.returnQ,row.remark8);
                        }
                    },
                    {
                        field: 'returnReason',
                        title: '退货理由',
                        valign: "middle",
                        align: "center"
                    }/* ,
                    {
                        field: 'dayConsumptionQ',
                        title: '日消耗量',
                        valign: "middle",
                        align: "center"
                    } */

                ]
            ]
        });
    }

    //根据传入的表格ID 查询数据
    function dedaoValue(tableId){

        //拿到原来表格中填写的订单号和时间
        var $thead  = $($($("#"+tableId)[0]).find("thead")[0]);
        //拿到第一行
        var $tr1 = $($thead.find("tr")[0]);
        //拿到订单号
        var number = $($($tr1.find("th")[1]).find("div")[0]).text();
        //拿到时间
        var time = $("#addTime").val();


        //拿到第二行
        var $tr2 = $($thead.find("tr")[1]);
        //拿到客户名称
        var customer = $($($tr2.find("th")[1]).find("div")[0]).text();
        console.log("customer--",customer);
        var obj = {
            number : number,
            time : time,
            customer : customer
        };
        return obj;
    }
</script>

<!--  时间插件   -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function () {
        var form = layui.form(),
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');
        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [/(.+){6,12}$/, '密码必须6到12位'],
            content: function (value) {
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function (data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });


</script>


<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script>
    //循环获取父层的tab对象，为什么用循环呢？因为子层加载完，父层还不一定加载完了。所以获取到的是undefined
    /*var index = setInterval(function() {
        if(typeof parent.tab !== 'undefined') {
            //如果获取到tab对象，则停止循环
            clearInterval(index);
            //通过调用父层的tab组件里的tabAdd方法添加一个tab选项卡
            parent.tab.tabAdd({
                href: 'https://www.baidu.com', //地址
                icon: 'fa-user',
                title: '这是在子窗口打开的tab选项卡'
            });
        }
    }, 20);*/
    //如果需要在些页面上获取到父页面的变量，需要把变量设置为全局，
    /**
     * 例：
     * var tab;
     * layui.use('tab',function(){
         * 	   tab = layui.tab(setting);
         * });
     */
    //上面那个是页面渲染完就添加的
    layui.use(['layer'], function () {
        var aa = 111;
        var $ = layui.jquery,
            layer = layui.layer;

        //移除当前的选项卡
        $('#remove').on('click', function () {
            var tab = parent.tab;

            tab.deleteTab(tab.getCurrentTabId());
        });

        //这个是点击之后才添加的。
        $('#btn_add').on('click', function () {

            window.location.href = "${pageContext.request.contextPath}/pages/yzlERP/return/add.jsp";

            //这是核心的代码。
            /*parent.tab.tabAdd({
                href: "/pages/yzlERP/return/add.jsp", //地址
                icon: "",
                title: "添加"
            });*/
        });
        $('#btn_edit').on('click', function () {

            //必须选中一条数据
            var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
            var checkedItem = checkedItems[0];
			console.log(checkedItem);
            if(checkedItems.length == 0){
            	toastrStyle();
                toastr.warning('请选择一行信息');
                
            }else if(checkedItems.length == 1){
            	
            	if(checkedItem.returnsExamineStatus=='0'){
            		window.location.href = "${pageContext.request.contextPath}/pages/yzlERP/return/update.jsp?id="+checkedItem.id;
            	}else{
            		toastrStyle();
            		toastr.warning('只能选择未审批的信息');
            	}
            
            } else{
            	toastrStyle();
            	toastr.warning('只能选择一行信息');
            	
            }


        });

    });
</script>
<script type="text/javascript">
 $(function () {
	$(".form_datetime").datetimepicker({
	 format: "yyyy-mm-dd",
	 autoclose: true,
	 todayBtn: true,
	 todayHighlight: true,
	 showMeridian: true,
	 pickerPosition: "bottom-left",
	 language: 'zh-CN',//中文，需要引用zh-CN.js包
	 startView: 2,//月视图
	 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
	 });
 });
</script>
</body>
</html>

<%--<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>销售退货</title>
    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/bootstrap/dist/js/bootstrap.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath }/bootstrap/dist/css/bootstrap.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath }/pages/yzl/css/test.css">
    <link rel="stylesheet" href="${pageContext.request.contextPath }plugins/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="${pageContext.request.contextPath }/plugins/font-awesome/css/font-awesome.min.css">
    <script src="${pageContext.request.contextPath }/bootstrap-cb/dist/bootstrap-table.js"></script>
    <link href="${pageContext.request.contextPath }/bootstrap-cb/dist/bootstrap-table.css" rel="stylesheet"/>
    <script src="${pageContext.request.contextPath }/bootstrap-cb/src/locale/bootstrap-table-zh-CN.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath }/plugins/layui/layui.js"></script>
    <script src="${pageContext.request.contextPath }/js/toastr.min.js"></script>
    <link href="${pageContext.request.contextPath }/css/toastr.min.css" rel="stylesheet"/>
    <script type="text/javascript">toastr.options.positionClass = 'toast-top-center';</script>
    <script type="text/javascript">
        $(function () {

            //1.初始化Table
            var oTable = new TableInit();
            oTable.Init();

            //2.初始化Button的点击事件
            var oButtonInit = new ButtonInit();
            oButtonInit.Init();

            /*$("#backOutLibNum").click(function (){
                console.log("//////////////////")
                backOutLibNum();
            })*/

        });


        var TableInit = function () {
            var oTableInit = new Object();
            //初始化Table
            oTableInit.Init = function () {
                $('#tb_departments').bootstrapTable({
                    url: '/pages/yzlERP/data/salesReturns.json',         //请求后台的URL（*）
                    method: 'post',                      //请求方式（*）
                    //contentType : "application/x-www-form-urlencoded",
                    toolbar: '#toolbar',                //工具按钮用哪个容器
                    striped: true,                      //是否显示行间隔色
                    cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                    pagination: true,                   //是否显示分页（*）
                    //queryParamsType: "limit",
                    //contentType: "application/x-www-form-urlencoded",
                    queryParams: oTableInit.queryParams,//传递参数（*）
                    sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                    pageNumber: 1,                       //初始化加载第一页，默认第一页
                    pageSize: 10,                       //每页的记录行数（*）
                    pageList: [5,10,15,20],        //可供选择的每页的行数（*）
                    strictSearch: true,
                    //clickToSelect: true,                //是否启用点击选中行
                    height: 400,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                    uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
                    showToggle: true,                    //是否显示详细视图和列表视图的切换按钮
                    cardView: false,                    //是否显示详细视图
                    detailView: false,                   //是否显示父子表
                    columns: [{
                        checkbox: true
                    }, /*{
                        field: 'id',
                        title: 'ID'
                    },*/ {
                        field: 'returnsNumber',
                        title: '退货编号'
                    }, {
                        field: 'returnsDate',
                        title: '退货日期'
                    }, {
                        field: 'customer',
                        title: '客户'
                    },
                    {
                        field: 'returnsStatus',
                        title: '状态',
                        formatter:function(value, row, index){
                            if(value == 0){
                                return '处理中'
                            }else if(value == 1){
                                return '退货成功'
                            }else{
                                return 'WTF'
                            }
                        }
                    }, {
                        field: 'returnsExamineStatus',
                        title: '审批状态',
                        formatter: function (value, row, index) {
                            var back = index;
                            if (value == "0") {
                                return '未提交审核'
                            } else if (value == "1") {
                                return '审核中'
                            } else if (value == "2") {
                                return '审核通过'
                            } else {
                                return 'WTF'
                            }
                        }
                    }]
                });
            };

            //得到查询的参数
            oTableInit.queryParams = function (params) {
                var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                    limit: params.limit,   //页面大小
                    offset: params.offset/params.limit+1,  //页码
                    demandDate: $("#demandDate_serch").val(),
                    produceStatus: $("#produceStatus_serch").val(),
                    outLibraryStatus: $("#outLibraryStatus_serch").val(),
                    customerId: $("#customerId_serch").val(),
                    entryPerson: $("#entryPerson_serch").val(),
                };
                return temp;
            };
            return oTableInit;
        };


        var ButtonInit = function () {

            var oInit = new Object();
            var postdata = {};

            oInit.Init = function () {
                //初始化页面上面的按钮事件
            };
            return oInit;
        };
    </script>
</head>
<body>

<div class="panel-body" style="padding-bottom:0px;">

    <!--     查询条件      -->
    <div class="panel panel-default">
        <div class="panel-body">
            <form id="formSearch" class="form-horizontal">
                    <label class="control-label col-sm-1" for="txt_search_departmentname">日期:</label>
                    <div class="col-sm-1">
                        <select id="txt_search_departmentname" name="materienumber" class="selectpicker show-tick form-control"  data-live-search="false">
                            <option>最近一天</option>
                            <option>最近一星期</option>
                            <option>最近一个月</option>
                        </select>
                    </div>
                    <label class="control-label col-sm-1" for="txt_search_statu" style="width: 30px;">从</label>
                    <div class="col-sm-2">
                        <input type="text" name="demandDate" id="demandDate_serch" lay-verify="date" placeholder="yyyy-mm-dd"
                               autocomplete="off" class="layui-input form-control"
                               onclick="layui.laydate({elem: this})">
                    </div>
                    <label class="control-label col-sm-1" for="txt_search_statu" style="width: 30px;padding-left: 0px;">至</label>
                    <div class="col-sm-2" style="padding-left: 0px;">
                        <input type="text" name="demandDate" id="demandDate_serch1" lay-verify="date" placeholder="yyyy-mm-dd"
                               autocomplete="off" class="layui-input form-control"
                               onclick="layui.laydate({elem: this})">
                    </div>
                    <label class="control-label col-sm-1" for="txt_search_departmentname">相关单位:</label>
                    <div class="col-sm-1">
                        <select id="txt_search_departmentname1" name="materienumber" class="selectpicker show-tick form-control"  data-live-search="false">
                            <option>所有客户</option>
                            <option>￥%……&*</option>
                            <option>*&……%￥</option>
                        </select>
                    </div>
                    <div class="col-sm-1" style="text-align:left;">
                        <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary">查询</button>
                    </div>
                    <div class="col-sm-1" style="text-align:left;">
                        <button type="button" id="btn_query3" class="btn btn-default">清除</button>
                    </div>
            </form>
        </div>
    </div>

    <!--     新建  修改 删除== 按钮     -->
    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新建
        </button>
        <button id="btn_edit" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
        <button id="btn_approved" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>审批
        </button>
        <button id="btn_approved2" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>批量审批
        </button>
        <button id="btn_Undoapproved" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>撤销审批
        </button>
        <button id="btn_Export" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>导出
        </button>
        <button id="btn_Export1" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>打印条形码
        </button>
        <button id="btn_Export2" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>退货处理
        </button>
    </div>

    <!--    模态框  新建  修改 按钮     -->
    <div id="toolbarIn" class="btn-group" style="display: none">
        <button id="btn_addIn" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_deleteIn" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
    </div>

    <!--        外面表格表格           -->
    <table id="tb_departments"></table>

    <!--      下面详情表格      -->
    <table id="td_bottomXqTable"></table>

    <!--          添加表单       -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 70%;height: 60%">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="myModalLabel">新增订单</h4>
                </div>

                <div id="outLibTable_outDiv"></div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary">确定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>

    <!--          销售出库选择列表       -->
    <div class="modal fade" id="salePlanModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 60%;height: 50%">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="salePlanModelLabel">出库单</h4>
                </div>

                <table id="td_outLibTable"></table>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="backOutLibNum()" id="backOutLibNum">确定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>


    <!--          客户选择表单       -->
    <div class="modal fade" id="customerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 60%;height: 50%">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                    <h4 class="modal-title" id="customerModalLabel">新增订单</h4>
                </div>

                <table id="td_customerTable"></table>

                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="backCus()" id="backCus">确定</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>

</div>



<script>


    $("#btn_add").click(function () {
        //initAddModelTable("0001","2222-2","小鬼","客户","000000001","小鬼");
        initAddModelTable("0001","2222-2","小鬼","","","小鬼");
    });

    $("#btn_edit").click(function () {

        if ($('#checkbox-id').is(':checked')) {
        }

        $('#myModalUpdate').modal({
            keyboard: true,
        })
    });
    $("#btn_delete").click(function () {

        if ($('#checkbox-id').is(':checked')) {
        }

        $('#myModalDelete').modal({
            keyboard: true,
        })
    });
    //提交审核
    $("#btn_approved").click(function (){
        //必须选中一条数据
        var checkedItems = $('#tb_departments').bootstrapTable('getSelections');
        var checkedItem = checkedItems[0];
        if(checkedItems <= 0){
            //$("#btn_edit").attr("data-toggle", "");
            //$("#btn_edit").attr("data-target", "");
            toastr.warning('请选择一行信息');
        }else{
            var arr = filterData(checkedItems);
            if(arr){
                //执行后台
                $.ajax({
                    url:"${pageContext.request.contextPath}/yzl/orderApproveds.do",
                    type:"post",
                    data:{"arr":JSON.stringify(arr)},
                    success:function (data) {
                        if(data != 0){
                            toastr.info('操作成功');
                            refreshAjax();
                        }else{
                            toastr.warning('操作失败');
                        }
                    }
                })
            }else{
                toastr.warning('不能选择审核中的审核通过的');
            }
        }
    })

    //选择客户 返回带回数据 关闭第二层模态框 第一层模态框表格重新加载
    function backCus(){

        //得到选择的数据
        var rows = $('#td_customerTable').bootstrapTable('getSelections')[0];
        //得到原来的表头信息
        var objTable = dedaoValue("td_addModelTable");
        if(rows){
            //关闭第二层模态框
            $("#backCus").attr("data-dismiss","modal");
            //更新第一层模态框的表格
            initAddModelTable(objTable.number,objTable.time,rows.name,rows.name,"1111",rows.name);
        }else{
            alert("请选择客户");
        }
    }

    //$($($($($($("#td_addModelTable")[0]).find("thead")[0]).find("tr")[1]).find("th")[3]).find("div")[1]).empty();
    //$($($($($($("#td_addModelTable")[0]).find("thead")[0]).find("tr")[1]).find("th")[3]).find("div")[1]).html("#$%^&*(");

    //选择客户
    function chosecustomer(){
    }
    //选择出库单
    function chosePlanNum(){
        initoutLibTable();
        $('#salePlanModel').modal({keyboard: true,})
    }

    //选择出库单 返回带回数据 关闭第二层模态框 第一层模态框表格重新加载
    function backOutLibNum(){

        //得到选择的数据
        var rows = $('#td_outLibTable').bootstrapTable('getSelections')[0];

        if(rows){
            //关闭第二层模态框
            $("#backOutLibNum").attr("data-dismiss","modal");
            //更新第一层模态框的表格
            initAddModelTable("0001",rows.returnDate,"大鬼","大鬼",rows.returnNumber,"大鬼");
        }else{
            alert("请先选择单号");
        }
    }

    //选择客户
    function choseCustomer(){initCustomerTable()}

    //计划详情
    function planXq(){
        initBottomXqTable();
    }

    //选中数据条件筛选
    function filterData(checkedItems){
        var arr = new Array();
        for(var i=0;i<checkedItems.length;i++){
            var orderExamineStatus = checkedItems[i].orderExamineStatus;
            if(orderExamineStatus == "2" || orderExamineStatus == "1"){
                return false
            }else{
                arr.push(checkedItems[i].id);
            }
        }
        return arr;
    }

    //点击查询 重新请求  刷新表格
    function refreshAjax(){
        $("#tb_departments").bootstrapTable('refresh',{url : '${pageContext.request.contextPath }/yzl/customerOrderList.do'});
    }
</script>




<!--   表格初始化    -->
<script>

    //初始化添加表格（为了更新表头数据）
    function initAddModelTable(number,time,zhidanMan,customer,beforeNumber,approvedMan){

        var $outLibTable_outDiv = $("#outLibTable_outDiv");
        if($outLibTable_outDiv.find("table").length > 0){
            $outLibTable_outDiv.empty();
        }
        var table = '<table id="td_addModelTable"></table>'
        $outLibTable_outDiv.append(table);


        if(beforeNumber == "" || beforeNumber == null){
            beforeNumber = '<a href="#" onclick="chosePlanNum()">选择出库单号</a>'
        }else{
            beforeNumber = '<a href="#" onclick="chosePlanNum()">'+beforeNumber+'</a>'
        }
        if(customer == "" || customer == null){
            customer = '<a href="#" onclick="choseCustomer()">选择客户</a>'
        }else{
            customer = '<a href="#" onclick="choseCustomer()">'+customer+'</a>'
        }


        $('#td_addModelTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            toolbar: '#toolbarIn',
            url:"/pages/yzlERP/data/saleOutCarList.json",
            columns:[
                [
                    {
                        field: 'name',
                        title: "出库单号",
                        valign:"middle",
                        align:"center",
                        colspan: 1
                    },
                    {
                        title: number,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: "出库日期",
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        /*title: '<input type="text" name="demandDate" id="demandDate_serch1" lay-verify="date"' +
                        '                               placeholder="yyyy-mm-dd"' +
                        '                               autocomplete="off" class="layui-input form-control"' +
                        '                               onclick="layui.laydate({elem: this})">',*/
                        title:time,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: "制单人",
                        valign:"middle",
                        align:"center",
                        colspan: 2,
                    },
                    {
                        title: zhidanMan,
                        valign:"middle",
                        align:"center",
                        colspan: 2,
                    }
                ],
                [
                    {
                        field: 'name',
                        title: '客户',
                        valign:"middle",
                        align:"center",
                        colspan: 1
                    },
                    {
                        //title: '<a href="#" onclick="choseCustomer()" >选择客户</a>',
                        title: customer,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: "销售计划单号",
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        //title: '<a href="#" onclick="chosePlanNum()">选择出库单号</a>',
                        title: beforeNumber,
                        //title: '<a href="#" onclick="chosePlanNum()" style="height: 20px;width: 20px">...</a>',
                        valign:"middle",
                        field: 'aa',
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: "审批人",
                        valign:"middle",
                        align:"center",
                        colspan: 2,
                    },
                    {
                        title: approvedMan,
                        valign:"middle",
                        align:"center",
                        colspan: 2,
                    }
                ],
                [
                    {
                        field: 'carType',
                        title: '车种',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'numberP',
                        title: '品编',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'nameP',
                        title: '品名',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'batchNumber',
                        title: '批号',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'barderNumber',
                        title: '条码',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'returnsQ',
                        title: '退货数量',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'returnsRes',
                        title: '退货原因',
                        valign:"middle",
                        align:"center"
                    },
                    {
                        field: 'returnsPeice',
                        title: '退货金额',
                        valign:"middle",
                        align:"center"
                    }
                ]
            ]
        });
        var allRows = $("#tb_departments").bootstrapTable("getData");
        $('#myModal').modal({keyboard: true,})
        $("#toolbarIn").css("display","block");

    }

    //初始化下面详情表格
    function initBottomXqTable(){
        $('#td_bottomXqTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            height:300,
            toolbar: '#toolbarIn',
            url: "/pages/yzlERP/data/carList.json",
            columns: [
                [
                    {
                        field: 'planNumber',
                        title: '计划单号',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'planDate',
                        title: '计划日期',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'customer',
                        title: '客户',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'carType',
                        title: '车种',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'numberP',
                        title: '品编',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'nameP',
                        title: '品名',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'planQ',
                        title: '计划数量',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'dayConsumptionQ',
                        title: '日消耗量',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'planWcDate',
                        title: '生产完成日期',
                        valign: "middle",
                        align: "center"
                    }

                ]
            ]
        });
    }

    //初始化出库单表格
    function initoutLibTable(){
        $('#td_outLibTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            height:300,
            singleSelect : true, // 单选checkbox
            url: "/pages/yzlERP/data/outLiblist.json",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'name',
                        title: '计划单号',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'customer',
                        title: '客户',
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field: 'returnDate',
                        title: '出库日期',
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
    }

    //初始化客户表单
    function initCustomerTable(){
        $('#td_customerTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            singleSelect : true, // 单选checkbox
            url: "/pages/yzlERP/data/customerList.json",
            columns: [
                [
                    { checkbox: true },
                    {
                        field: 'name',
                        title: "名称",
                        valign: "middle",
                        align: "center"
                    },
                    {
                        field:"age",
                        title: "年龄",
                        valign: "middle",
                        align: "center"
                    }
                ]
            ]
        });
        $("#customerModal").modal({keyboard: true,})
    }

    //更具传入的表格ID 查询数据
    function dedaoValue(tableId){

        //拿到原来表格中填写的订单号和时间
        var $thead  = $($($("#"+tableId)[0]).find("thead")[0]);
        //拿到第一行
        var $tr1 = $($thead.find("tr")[0]);
        //拿到订单号
        var number = $($($tr1.find("th")[1]).find("div")[0]).text();
        //拿到时间
        var time = $("#addTime").val();


        //拿到第二行
        var $tr2 = $($thead.find("tr")[1]);
        //拿到客户名称
        var customer = $($($tr2.find("th")[1]).find("div")[0]).text();
        console.log("customer--",customer);
        var obj = {
            number : number,
            time : time,
            customer : customer
        };
        return obj;
    }
</script>


<!--      时间插件       -->
<script>
    layui.use(['form', 'layedit', 'laydate'], function() {
        var form = layui.form(),
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');
        //自定义验证规则
        form.verify({
            title: function(value) {
                if(value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [/(.+){6,12}$/, '密码必须6到12位'],
            content: function(value) {
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function(data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });
</script>

</body>
</html>--%>

